package xju.rjxy.shop.web.controller;

import com.alibaba.fastjson.JSON;
import xju.rjxy.shop.common.framework.simplemvc.RequestMapping;
import xju.rjxy.shop.common.utils.JSONUtil;
import xju.rjxy.shop.common.utils.Result;
import xju.rjxy.shop.model.domain.Friend;
import xju.rjxy.shop.model.vo.FriendVO;
import xju.rjxy.shop.model.vo.UserWithGamesVO;
import xju.rjxy.shop.service.IFriendService;
import xju.rjxy.shop.service.IUserService;
import xju.rjxy.shop.service.impl.FriendServiceImpl;
import xju.rjxy.shop.service.impl.UserServiceImpl;
import xju.rjxy.shop.model.vo.UserVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * 好友控制层
 */
@RequestMapping("/api/friend")
public class FriendController {
    private final IFriendService friendService = new FriendServiceImpl();
    private final IUserService userService = new UserServiceImpl();

    @RequestMapping("/list.do")
    public void getFriendList(HttpServletRequest request, HttpServletResponse response) {
        // TODO 条件查询列表
        List<FriendVO> friendList = friendService.getFriendList();
        JSONUtil.printByJSON(response, Result.success(friendList));
    }
    
    @RequestMapping("/user.do")
    public void getFriendListByUserId(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            if (userIdStr == null || userIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            List<FriendVO> friendList = friendService.getFriendListByUserId(userId);
            JSONUtil.printByJSON(response, Result.success(friendList));
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/tag.do")
    public void getFriendListByTag(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String tag = request.getParameter("tag");
            
            if (userIdStr == null || userIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            if (tag == null || tag.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("分组名称不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            List<FriendVO> friendList = friendService.getFriendListByTag(userId, tag);
            JSONUtil.printByJSON(response, Result.success(friendList));
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/delete.do")
    public void deleteFriend(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取JSON请求体
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String body = sb.toString();
            System.out.println("[deleteFriend] 请求体: " + body);
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSON.parseObject(body);
            Integer userId = json.getInteger("userId");
            Integer friendId = json.getInteger("friendId");
            System.out.println("[deleteFriend] userId=" + userId + ", friendId=" + friendId);

            if (userId == null || friendId == null) {
                JSONUtil.printByJSON(response, Result.fail("用户ID和好友ID不能为空"));
                return;
            }

            boolean success = friendService.deleteFriend(userId, friendId);
            System.out.println("[deleteFriend] 删除结果: " + success);

            if (success) {
                JSONUtil.printByJSON(response, Result.success("删除成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("删除失败"));
            }

        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/searchFriend.do")
    public void searchFriend(HttpServletRequest request, HttpServletResponse response) {
        try {
            String friendKeyword = request.getParameter("friendKeyword");

            if (friendKeyword == null || friendKeyword.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("好友关键词不能为空"));
                return;
            }

            // 根据关键词搜索完整用户信息
            UserVO userVO = userService.findUserVOByUsernameOrPhone(friendKeyword);
            if (userVO == null) {
                JSONUtil.printByJSON(response, Result.fail("未找到该用户"));
            } else {
                JSONUtil.printByJSON(response, Result.success(userVO));
            }

        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/searchFriendWithGames.do")
    public void searchFriendWithGames(HttpServletRequest request, HttpServletResponse response) {
        try {
            String friendKeyword = request.getParameter("friendKeyword");

            if (friendKeyword == null || friendKeyword.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("好友关键词不能为空"));
                return;
            }

            // 根据关键词搜索包含游戏库的完整用户信息
            UserWithGamesVO userWithGamesVO = userService.findUserWithGamesByUsernameOrPhone(friendKeyword);
            if (userWithGamesVO == null) {
                JSONUtil.printByJSON(response, Result.fail("未找到该用户"));
            } else {
                JSONUtil.printByJSON(response, Result.success(userWithGamesVO));
            }

        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }

    @RequestMapping("/addFriend.do")
    public void addFriend(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String friendIdStr = request.getParameter("friendId");
            String tag = request.getParameter("tag");
            if (userIdStr == null || friendIdStr == null) {
                JSONUtil.printByJSON(response, Result.fail("参数不完整"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            Integer friendId = Integer.parseInt(friendIdStr);
            if (userId.equals(friendId)) {
                JSONUtil.printByJSON(response, Result.fail("不能添加自己为好友"));
                return;
            }
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setTag(tag);
            // flag和statusCode由Service层设置
            boolean success = friendService.addFriend(friend);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("好友申请已发送"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("添加好友失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/updateTag.do")
    public void updateFriendTag(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String friendIdStr = request.getParameter("friendId");
            String tag = request.getParameter("tag");
            
            if (userIdStr == null || friendIdStr == null || tag == null) {
                JSONUtil.printByJSON(response, Result.fail("参数不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            Integer friendId = Integer.parseInt(friendIdStr);
            
            boolean success = friendService.updateFriendTag(userId, friendId, tag);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("更新成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("更新失败"));
            }
            
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/info.do")
    public void getFriendInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String friendIdStr = request.getParameter("friendId");
            if (userIdStr == null || friendIdStr == null) {
                JSONUtil.printByJSON(response, Result.fail("用户ID和好友ID不能为空"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            Integer friendId = Integer.parseInt(friendIdStr);
            FriendVO friendVO = friendService.getFriendInfo(userId, friendId);
            if (friendVO != null) {
                JSONUtil.printByJSON(response, Result.success(friendVO));
            } else {
                JSONUtil.printByJSON(response, Result.fail("好友不存在"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/accept.do")
    public void acceptFriend(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String friendIdStr = request.getParameter("friendId");
            if (userIdStr == null || friendIdStr == null) {
                JSONUtil.printByJSON(response, Result.fail("参数不完整"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            Integer friendId = Integer.parseInt(friendIdStr);
            boolean success = friendService.acceptFriend(userId, friendId);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("已同意好友申请"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("操作失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/requestList.do")
    public void getFriendRequestList(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            if (userIdStr == null) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            List<FriendVO> requestList = friendService.getPendingRequestList(userId);
            JSONUtil.printByJSON(response, Result.success(requestList));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/reject.do")
    public void rejectFriend(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String friendIdStr = request.getParameter("friendId");
            if (userIdStr == null || friendIdStr == null) {
                JSONUtil.printByJSON(response, Result.fail("参数不完整"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            Integer friendId = Integer.parseInt(friendIdStr);
            boolean success = friendService.rejectFriend(userId, friendId);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("已拒绝好友申请"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("操作失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/allWithPending.do")
    public void getAllFriendsWithPending(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            if (userIdStr == null) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            List<FriendVO> list = friendService.getAllFriendsWithPending(userId);
            JSONUtil.printByJSON(response, Result.success(list));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/allWithPendingPage.do")
    public void getAllFriendsWithPendingPage(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String pageNumStr = request.getParameter("pageNum");
            String pageSizeStr = request.getParameter("pageSize");
            if (userIdStr == null || pageNumStr == null || pageSizeStr == null) {
                JSONUtil.printByJSON(response, Result.fail("参数不能为空"));
                return;
            }
            Integer userId = Integer.parseInt(userIdStr);
            int pageNum = Integer.parseInt(pageNumStr);
            int pageSize = Integer.parseInt(pageSizeStr);
            List<FriendVO> list = friendService.getAllFriendsWithPendingPage(userId, pageNum, pageSize);
            int total = friendService.getAllFriendsWithPendingTotal(userId);
            java.util.Map<String, Object> data = new java.util.HashMap<>();
            data.put("list", list);
            data.put("total", total);
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("code", 200);
            result.put("data", data);
            result.put("success", true);
            JSONUtil.printByJSON(response, result);
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }

    /**
     * 读取请求体并转换为指定类型
     */
    private <T> T readRequestBody(HttpServletRequest request, Class<T> clazz) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return JSON.parseObject(sb.toString(), clazz);
    }
}